<template>
  <div>
    <div class="lists_tit" />
    <div class="lists-box">
      <el-button v-if="isShow" size="small" type="primary" @click="zxAdd">新增文章</el-button>
      <el-input v-model="query.title" class="input-with-select" clearable style="width: 530px;" placeholder="请输入标题">
        <el-button slot="append" icon="el-icon-search" @click="search" />
      </el-input>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column label="标题" prop="title" />
      <el-table-column label="创建人" prop="updateBy" width="180" />
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="routerDetails(scope.row)">查看</el-button>
          <el-button v-if="isShow" size="small" type="text" @click="editArticle(scope.row)">编辑</el-button>
          <el-button v-if="isShow" size="small" type="text" @click="delBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: center;padding: 20px;"
      :current-page="query.current"
      :page-size="query.size"
      :page-sizes="[10, 20, 30, 40]"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--    新增弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisibleXz" width="1000px">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <vue-editor v-model="ruleForm.content" :toolbar="customToolbar" />
        </el-form-item>
        <el-form-item label="上传附件">
          <el-upload
            :action="zymlUrl + '/api/dataFile/add/' + uuid"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-remove="beforeRemove"
            :headers="headers"
            :file-list="fileList"
            :show-file-list="true"
            :auto-upload="true"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleXz = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 详情对话框组件 -->
    <news-detail-dialog :visible.sync="showDetailDialog" :detail-data="detailData" @clearDetailData="detailData = {}" @download="handleDownload" />
  </div>
</template>
<script>
import axios from 'axios'
// 引入详情对话框组件
import NewsDetailDialog from '@/views/TaskManagement/XinWenZiXun/NewsDetailDialog.vue'
import { VueEditor } from 'vue2-editor'
import { addl, deletel, editl, listll, detail, downloadFile } from '@/api/xwZx.js'
import { getToken } from '@/utils/auth'
export default {
  components: { VueEditor, NewsDetailDialog },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      zymlUrl: process.env.VUE_APP_BASE_API,
      // 新增详情对话框相关数据
      showDetailDialog: false, // 控制详情对话框显示
      detailData: {}, // 详情数据
      customToolbar: [
        ['bold', 'italic', 'underline', 'strike'], // 基础文本样式
        ['blockquote', 'code-block'], // 引用、代码块
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
        [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
        [{ 'direction': 'rtl' }], // 文本方向
        [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
        [{ 'color': [] }, { 'background': [] }], // 颜色
        [{ 'font': [] }], // 字体
        [{ 'align': [] }], // 对齐方式
        ['link'], // 保留链接功能（移除了"image"和"video"）
        ['clean'] // 清除格式
      ],
      uuid: '',
      isShow: true,
      ids: '',
      dialogTitle: '',
      options: [],
      dialogFormVisibleXz: false,
      formattedDate: '', // 用于存储格式化后的日期
      query: {
        title: '',
        current: 1,
        size: 10
      },
      totalCount: 0,
      tableData: [],
      ruleForm: {
        title: '',
        // 名称
        location: '', // 上传文件 id
        content: '',
        // type: '',
        id: '',
        fileIds: []
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      fileList: []
    }
  },
  watch: {
    dialogFormVisibleXz(n, o) {
      if (n) {
        this.$nextTick(() => {
          document.getElementsByClassName('ql-video')[0].style.display = 'none'
        })
      }
    }
  },
  mounted() {
    this.getlist()
  },
  methods: {
    handleDownload(item) {
      downloadFile(item.id).then(res => {
        // 3. 将 blob 转换为可下载的链接
        const blob = new Blob([res], {
          // 根据文件类型设置 MIME 类型
          // 常见类型：application/pdf、image/jpeg、application/vnd.ms-excel 等
          type: 'application/octet-stream'
        })

        // 4. 创建 a 标签并触发下载
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = item.name
        document.body.appendChild(a)
        a.click() // 触发点击下载

        // 5. 清理资源
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url) // 释放 blob URL

        this.$message.success('文件下载成功')
      })
    },
    // 查看详情方法修改
    routerDetails(row) {
      // 显示对话框
      this.showDetailDialog = true
      // 获取详情数据
      detail(row.id).then(res => {
        console.log('详情数据', res)
        this.detailData = res
      })
    },
    getuuid() {
      this.uuid = this.guid()
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0; var v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },
    editArticle(row) {
      this.ids = row.id
      console.log(row, '编辑回显')
      this.dialogFormVisibleXz = true
      this.dialogTitle = '编辑'
      this.getuuid()
      detail(row.id).then(res => {
        console.log(res, '编辑回显')
        this.ruleForm.title = res.title
        this.ruleForm.content = res.content
        this.ruleForm.type = res.type
        this.ruleForm.fileIds = res.list.map(file => file.id) || []
        this.fileList = res.list.map(file => ({
          id: file.id,
          name: file.name, // 后端返回的文件名
          url: `${this.zymlUrl}/api/dataFile/download/${file.id}`, // 下载地址
          size: file.fileSize // 可选，显示文件大小
        }))
      })
    },
    delBtn(row) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          deletel({ id: row.id }).then(res => {
            console.log(res, '删除')
            this.$message.success('删除成功')
            this.getlist()
          })
        })
        .catch(() => {
        })
    },
    zxAdd() {
      this.dialogFormVisibleXz = true
      this.dialogTitle = '新增'
      this.ruleForm = {
        title: '',
        content: '',
        id: '',
        fileIds: [] // 明确重置为数组
      }
      this.fileList = []
      // 点击新增弹窗 生成uuid
      this.getuuid()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === '新增') {
            const formattedRuleForm = {
              ...this.ruleForm,
              title: this.ruleForm.title, // 修复：编辑时传递标题（原代码缺失）
              fileIds: this.ruleForm.fileIds, // 新增：传递文件 ID 数组
              id: this.uuid
            }
            addl(formattedRuleForm).then((res) => {
              console.log(res, '新增')
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.fileList = []
              this.dialogFormVisibleXz = false
              this.resetForm('ruleForm')
              this.getlist()
            })
          }
          if (this.dialogTitle === '编辑') {
            const formattedRuleForm = {
              content: this.ruleForm.content,
              location: this.ruleForm.location,
              id: this.ids
            }
            editl(formattedRuleForm).then((res) => {
              console.log(res, '编辑')
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.fileList = []
              this.dialogFormVisibleXz = false
              this.resetForm('ruleForm')
              this.getlist()
            })
          }
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      // 调用删除接口，添加headers
      axios.post(
        `${this.zymlUrl}/api/dataFile/deleteDataFile/${file.id}`,
        {}, // 这里是请求体，删除接口如果不需要可以传空对象
        {
          headers: this.headers // 添加请求头
        }
      )
        .then(() => {
          this.$message.success(`文件 "${file.name}" 已删除`)
          // 从表单数据中移除该文件ID
          this.removeFileFromForm(file.id)
        })
    },
    // 从表单数据中移除文件ID
    removeFileFromForm(fileId) {
      this.ruleForm.fileIds = this.ruleForm.fileIds.filter(id => id !== fileId)
    },
    handleSuccess(response, file, fileList) {
      // 验证返回数据结构是否完整
      if (response && response.id) {
        // 找到当前文件在列表中的位置
        const index = fileList.findIndex(f => f.uid === file.uid)
        if (index !== -1) {
          // 根据返回数据结构精确映射文件信息
          fileList[index] = {
            ...fileList[index],
            id: response.id,
            name: response.name,
            size: response.fileSize,
            createTime: response.createTime,
            url: `${this.zymlUrl}/api/dataFile/download/${response.id}`,
            // 保存完整的响应数据以备后续使用
            fullInfo: response
          }
        }

        // 显示更详细的成功信息
        this.$message.success(`文件 "${response.name}" 上传成功 (${response.fileSize})`)

        // 可以在这里将文件ID同步到表单数据中
        this.syncFileToForm(response.id)
      } else {
        this.$message.error('文件上传成功，但返回数据格式不正确')
        console.error('上传成功但数据格式异常:', response)
      }
    },
    syncFileToForm(fileId) {
      // 第一步：判断 ruleForm.fileIds 是否存在，不存在则初始化
      if (!this.ruleForm.fileIds) {
        this.ruleForm.fileIds = []
      }
      // 第二步：再判断文件ID是否已存在，避免重复添加
      if (!this.ruleForm.fileIds.includes(fileId)) {
        this.ruleForm.fileIds.push(fileId)
      }
    },
    beforeRemove(file) {
      return this.$confirm(`确定要删除文件 "${file.name}" 吗？`)
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`最多只能上传1个文件`);
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeUpload(file) {
      // this.uploading = true; // 开始上传时显示进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = ''; // 重置上传状态
    },
    handleProgress(event, file, fileList) {
      // this.progress = Math.round(event.percent); // 更新进度条
    },
    handleError(error, file, fileList) {
      let errorMsg = `文件 "${file.name}" 上传失败`

      // 解析可能的错误信息
      if (error.response && error.response.data && error.response.data.msg) {
        errorMsg += `: ${error.response.data.msg}`
      } else if (error.message) {
        errorMsg += `: ${error.message}`
      }

      this.$message.error(errorMsg)
      console.error('上传错误:', error)
    },
    handleSizeChange(val) {
      this.query.size = val
      this.getlist()
    },
    handleCurrentChange(val) {
      this.query.current = val
      this.getlist()
    },
    getlist() {
      listll(this.query).then((res) => {
        console.log(res, 'list')
        this.tableData = res.content
        this.totalCount = res.totalElements
      })
    },
    search() {
      this.query.current = 1
      // 强制关闭对话框，确保状态重置
      this.showDetailDialog = false
      // 清空详情数据（可选，避免残留数据）
      this.detailData = {}
      this.getlist()
    }
  }
}
</script>
<style lang="scss" scoped>
.lists_tit {
  p {
    font-size: 17px;
    color: #256cd9;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #e6e6e6;
  }
}

.lists-box {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;

  .list_title {
    font-size: 18px;
    border-bottom: 2px solid #149bff;

    span {
      color: #149bff;
    }
  }

  .input-with-select {
    width: 50%;
  }
}

.el-table {
  border-top: 1px solid #ededed;
}

/* 重点修改：添加 ::v-deep 穿透 scoped 限制 */
/* 修复加粗样式不生效的问题 */
::v-deep .ql-editor strong,
::v-deep .ql-editor b,
::v-deep .ql-editor span[style*="font-weight: bold"] {
  font-weight: 700 !important;
}

/* 修复倾斜样式不生效的问题 */
::v-deep .ql-editor em,
::v-deep .ql-editor i,
::v-deep .ql-editor span[style*="font-style: italic"] {
  font-style: italic !important;
}

/* 确保编辑器内容区域的基础样式正确 */
::v-deep .ql-editor {
  font-weight: 400;
  /* 默认正常字重 */
  font-style: normal;
  /* 默认不倾斜 */
}

/* 新增：覆盖 Quill 自带样式冲突 */
::v-deep .ql-snow .ql-editor strong,
::v-deep .ql-snow .ql-editor b {
  font-weight: 700 !important;
}

::v-deep .ql-snow .ql-editor em,
::v-deep .ql-snow .ql-editor i {
  font-style: italic !important;
}
</style>
